<template>
  <div class="user-info">
    <div class="user-info-container">
      <h1>用户信息</h1>
      <!-- 用户未登录状态 - 普通提示 -->
      <div v-if="!isLoggedIn" class="login-prompt">
        <div class="prompt-icon">
          <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12 12C14.7614 12 17 9.76142 17 7C17 4.23858 14.7614 2 12 2C9.23858 2 7 4.23858 7 7C7 9.76142 9.23858 12 12 12Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            <path d="M20.59 22C20.59 18.13 16.74 15 12 15C7.26 15 3.41 18.13 3.41 22" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </div>
        <h3>用户信息</h3>
        <p class="prompt-message">登录后可查看和管理您的个人信息</p>
        <div class="prompt-actions">
          <button class="login-btn" @click="goToLogin">登录</button>
          <button class="register-btn" @click="goToRegister">注册</button>
        </div>
      </div>

      <!-- 用户已登录状态 -->
      <div v-else class="user-details">
        <!-- 用户头像部分 -->
        <div class="avatar-section">
          <div class="avatar-container" @click="showAvatarModal = true">
            <img :src="userAvatar" :alt="userData.nickname || '用户头像'" class="user-avatar" />
            <div class="avatar-overlay">
              <span class="avatar-hint">点击查看大图</span>
            </div>
          </div>
        </div>

        <!-- 用户信息部分 -->
        <div class="info-section">
          <div class="info-item">
            <span class="label">昵称：</span>
            <span class="value">{{ userData.nickname || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">性别：</span>
            <span class="value">{{ getGenderDisplay(userData.gender) }}</span>
          </div>
          <div class="info-item">
            <span class="label">生日：</span>
            <span class="value">{{ formatBirthday(userData.birthday) }}</span>
          </div>
          <div class="info-item">
            <span class="label">地址：</span>
            <span class="value">{{ userData.address || '未设置' }}</span>
          </div>
        </div>

        <!-- 操作按钮部分 -->
        <div class="actions">
          <button class="edit-btn" @click="openEditModal">编辑信息</button>
          <button class="logout-btn" @click="handleLogout">退出</button>
        </div>
      </div>
    </div>

    <!-- 编辑信息弹窗 -->
    <div v-if="showEditModal" class="edit-modal-overlay" @click.self="closeEditModal">
      <div class="edit-modal">
        <div class="edit-modal-header">
          <h3>编辑顾客信息</h3>
          <button class="close-btn" @click="closeEditModal">&times;</button>
        </div>
        <div class="edit-modal-body">
          <form @submit.prevent="handleUpdate">
            <div class="form-group">
              <label for="nickname">昵称</label>
              <input
                id="nickname"
                v-model="editForm.nickname"
                type="text"
                placeholder="请输入昵称"
                maxlength="20"
              />
            </div>

            <div class="form-group">
              <label for="gender">性别</label>
              <select id="gender" v-model="editForm.gender">
                <option value="">请选择</option>
                <option value="1">男</option>
                <option value="2">女</option>
              </select>
            </div>

            <div class="form-group">
              <label for="birthday">生日</label>
              <input
                id="birthday"
                v-model="editForm.birthday"
                type="date"
              />
            </div>

            <div class="form-group">
              <label for="address">地址</label>
              <input
                id="address"
                v-model="editForm.address"
                type="text"
                placeholder="请输入地址"
                maxlength="100"
              />
            </div>

            <div class="form-footer">
              <button type="button" class="cancel-btn" @click="closeEditModal">取消</button>
              <button type="submit" class="submit-btn" :disabled="updating">{{ updating ? '更新中...' : '保存' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 头像放大弹窗 -->
    <div v-if="showAvatarModal" class="avatar-modal-overlay" @click.self="closeAvatarModal">
      <div class="avatar-modal">
        <div class="avatar-modal-header">
          <h3>头像预览</h3>
          <button class="close-btn" @click="closeAvatarModal">&times;</button>
        </div>
        <div class="avatar-modal-body">
          <div class="large-avatar-container">
            <img 
              :src="avatarPreviewUrl || userAvatar" 
              :alt="userData.nickname || '用户头像'" 
              class="large-avatar" 
            />
          </div>
          <div class="avatar-upload-section">
            <input
              id="avatar-upload"
              type="file"
              accept="image/*"
              @change="handleAvatarSelect"
              style="display: none;"
            />
            <button
              class="upload-avatar-btn"
              @click="triggerFileSelect"
              :disabled="uploadingAvatar"
            >
              {{ selectedAvatar ? '更换图片' : '选择头像' }}
            </button>
            <button
              class="confirm-upload-btn"
              @click="handleAvatarUpload"
              :disabled="uploadingAvatar || !selectedAvatar"
            >
              {{ uploadingAvatar ? '上传中...' : '确认修改' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.user-info {
  min-height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  padding: 20px;
  width: 100%;
  height: 94.3vh;
}

.user-info-container {
  width: 100%;
  max-width: 600px;
  padding: 30px;
  background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  animation: fadeIn 0.6s ease;
  margin: 0;
}

.user-info-container h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 28px;
  font-weight: 700;
}

/* 编辑按钮样式 */
.edit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 40px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 15px;
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

.edit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.edit-btn:active {
  transform: translateY(0);
}

/* 编辑弹窗样式 */
.edit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
  animation: fadeIn 0.3s ease;
}

.edit-modal {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  animation: slideIn 0.4s ease;
}

.edit-modal-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 16px 16px 0 0;
}

.edit-modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.close-btn:hover {
  background-color: rgba(255, 255, 255, 0.2);
}

.edit-modal-body {
  padding: 25px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
  font-size: 15px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease;
}

.form-group input:focus,
.form-group select:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-footer {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 15px;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e0e0e0;
  color: #333;
}

.submit-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.submit-btn:active:not(:disabled) {
  transform: translateY(0);
}

.submit-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 响应式设计 - 编辑表单 */
@media (max-width: 480px) {
  .edit-modal {
    width: 95%;
    margin: 10px;
  }

  .edit-modal-body {
    padding: 20px;
  }

  .form-footer {
    flex-direction: column;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }

  .edit-btn {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }

  .actions {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .logout-btn {
    width: 100%;
  }

  /* 登录提示响应式 */
  .login-prompt {
    padding: 30px 15px;
  }

  .prompt-actions {
    flex-direction: column;
    align-items: center;
  }

  .login-btn,
  .register-btn {
    width: 100%;
    max-width: 280px;
    margin-bottom: 10px;
  }

  .register-btn {
    margin-bottom: 0;
  }
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 40px 20px;
  animation: fadeIn 0.6s ease;
  background: linear-gradient(135deg, #f0f2f5 0%, #e0e5ec 100%); /* 浅色渐变背景 */
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  margin: 20px auto; /* 居中显示 */
  max-width: 500px; /* 限制最大宽度 */
  border: 1px solid #dcdfe6;
}

.prompt-icon {
  margin-bottom: 25px;
  color: #667eea;
  display: flex;
  justify-content: center;
  font-size: 72px; /* 增大图标 */
}

.login-prompt h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 28px; /* 增大标题 */
  font-weight: 700;
}

.prompt-message {
  margin: 0 0 35px 0;
  color: #666;
  font-size: 18px; /* 增大消息文本 */
  line-height: 1.8;
}

.prompt-actions {
  display: flex;
  justify-content: center;
  gap: 20px; /* 增大按钮间距 */
  flex-wrap: wrap;
}

.login-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 14px 35px; /* 增大按钮 */
  border-radius: 30px; /* 更圆润的按钮 */
  font-size: 18px; /* 增大字体 */
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.login-btn:hover {
  transform: translateY(-3px); /* 更明显的悬停效果 */
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);
}

.login-btn:active {
  transform: translateY(0);
}

.register-btn {
  background: transparent;
  color: #667eea;
  border: 2px solid #667eea;
  padding: 12px 35px; /* 增大按钮 */
  border-radius: 30px; /* 更圆润的按钮 */
  font-size: 18px; /* 增大字体 */
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 140px;
}

.register-btn:hover {
  background: #667eea;
  color: white;
  transform: translateY(-3px); /* 更明显的悬停效果 */
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.5);
}

.register-btn:active {
  transform: translateY(0);
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideIn {
  from {
    transform: translateY(-50px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 用户详情样式 */
.user-details {
  animation: fadeIn 0.6s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

/* 头像部分 */
.avatar-section {
  margin-bottom: 15px;
}

.avatar-container {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid #f0f0f0;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: transform 0.6s ease, box-shadow 0.6s ease;
  position: relative;
}

.avatar-container:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-hint {
  color: white;
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  padding: 0 10px;
}

/* 头像弹窗样式 */
.avatar-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 3000;
  animation: fadeIn 0.3s ease;
}

.avatar-modal {
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  animation: slideIn 0.4s ease;
}

.avatar-modal-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 16px 16px 0 0;
}

.avatar-modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.avatar-modal-body {
  padding: 30px;
  text-align: center;
}

.large-avatar-container {
  margin-bottom: 25px;
  display: flex;
  justify-content: center;
}

.large-avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  object-fit: cover;
  border: 5px solid #f0f0f0;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.avatar-upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.upload-avatar-btn,
.confirm-upload-btn {
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  min-width: 150px;
}

.upload-avatar-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
}

.upload-avatar-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}

.confirm-upload-btn {
  background: linear-gradient(135deg, #4caf50 0%, #8bc34a 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(76, 175, 80, 0.3);
}

.confirm-upload-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
}

.upload-avatar-btn:disabled,
.confirm-upload-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.selected-file-info {
  color: #666;
  font-size: 14px;
  margin-top: 10px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式设计 - 头像弹窗 */
@media (max-width: 480px) {
  .avatar-modal {
    width: 95%;
    margin: 10px;
  }

  .avatar-modal-body {
    padding: 20px;
  }

  .large-avatar {
    width: 160px;
    height: 160px;
  }

  .upload-avatar-btn,
  .confirm-upload-btn {
    width: 100%;
    min-width: unset;
  }
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 信息部分 */
.info-section {
  width: 100%;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 12px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
}

.info-item {
  margin-bottom: 18px;
  padding: 12px 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
}

.info-item:last-child {
  margin-bottom: 0;
}

.info-item:hover {
  transform: translateX(5px);
}

.info-item .label {
  font-weight: 600;
  color: #666;
  margin-right: 12px;
  display: inline-block;
  min-width: 60px;
}

.info-item .value {
  color: #333;
  font-size: 15px;
}

/* 操作按钮部分 */
.actions {
  margin-top: 20px;
}

.logout-btn {
  background: linear-gradient(135deg, #ff5e62 0%, #ff9966 100%);
  color: white;
  border: none;
  padding: 12px 40px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 10px rgba(255, 94, 98, 0.3);
}

.logout-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(255, 94, 98, 0.4);
}

.logout-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .user-info-container {
    padding: 20px;
  }

  .avatar-container {
    width: 100px;
    height: 100px;
  }

  .info-section {
    padding: 15px;
  }

  .info-item {
    padding: 10px;
  }
}
</style>

<script>
import { ref, computed, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { getCustomerInfoById, updateCustomerInfo, updateCustomerAvatar } from '../api/user.js'

export default {
  name: 'UserInfo',
  setup() {
    const router = useRouter()
    const { proxy } = getCurrentInstance() || {}
    const isLoggedIn = ref(false)
    const userData = ref({})
    const showEditModal = ref(false)
    const updating = ref(false)
    const showAvatarModal = ref(false)
    const uploadingAvatar = ref(false)
    const selectedAvatar = ref(null)
    const avatarPreviewUrl = ref(null)
    const editForm = ref({
      id: '',
      nickname: '',
      gender: '',
      birthday: '',
      address: ''
    })

    // 检查登录状态并获取用户信息
    const checkLoginStatus = async () => {
      const token = localStorage.getItem('userToken')
      const userRoles = localStorage.getItem('userRoles')
      const userInfoStr = localStorage.getItem('userInfo')

      // 检查token和roles是否都存在，并验证是否有CUSTOMER角色
      if (token && userRoles) {
        try {
          const roles = JSON.parse(userRoles)
          const hasCustomerRole = roles.some(role => role.code === 'CUSTOMER')
          if (hasCustomerRole) {
            isLoggedIn.value = true
          } else {
            isLoggedIn.value = false
            return
          }
        } catch (error) {
          console.error('解析userRoles失败:', error)
          isLoggedIn.value = false
          return
        }
      } else {
        isLoggedIn.value = false
        return
      }

      if (isLoggedIn.value) {

        try {
          // 先从本地存储获取基本信息
          if (userInfoStr) {
            const localUserInfo = JSON.parse(userInfoStr)
            userData.value = localUserInfo
          }

          // 从userRoles数组中获取customerId
          const userRolesStr = localStorage.getItem('userRoles')
          let customerId = null
          
          if (userRolesStr) {
            try {
              const userRoles = JSON.parse(userRolesStr)
              const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
              if (customerRole) {
                customerId = customerRole.id
                console.log('从userRoles中获取到customerId:', customerId)
              }
            } catch (error) {
              console.error('解析userRoles失败:', error)
            }
          }

          // 如果有customerId，使用它调用API
          if (customerId) {
            console.log('使用从userRoles获取的顾客ID:', customerId)
            await fetchUserDetails(customerId)
            return
          }

          // 如果没有获取到有效的customerId，显示提示信息
          console.log('未找到有效的顾客ID，不使用默认值')
          // 不使用默认值，避免所有用户都获取到相同的顾客信息
          if (import.meta.env.DEV) {
            console.warn('请先登录以查看个人信息')
          }

        } catch (error) {
          console.error('获取或解析顾客信息失败:', error)
          // 即使API调用失败，保持登录状态，使用本地数据
        }
      } else {
        isLoggedIn.value = false
      }
    }

    // 从后端获取顾客详细信息
    const fetchUserDetails = async (customerId) => {
      console.log('开始获取顾客详情，customerId:', customerId)
      try {
        const response = await getCustomerInfoById(customerId)
        console.log('获取顾客详情响应:', response)
        // 检查响应是否存在且包含必要的顾客信息字段
        if (response && (response.id || response.nickname)) {
          // 更新顾客信息，确保与后端CustomerMessageVO结构匹配
          const userInfo = {
            id: response.id || userData.value.id,
            nickname: response.nickname || userData.value.nickname || '顾客',
            gender: response.gender !== undefined ? response.gender : userData.value.gender,
            birthday: response.birthday || userData.value.birthday,
            address: response.address || userData.value.address || '未设置',
            avatarUrl: response.avatarUrl || userData.value.avatarUrl
          }

          // 更新本地数据
          userData.value = userInfo
          // 更新本地存储
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
          console.log('顾客信息更新成功，与CustomerMessageVO结构匹配:', userInfo)

          // 检查地址是否为空，如果为空则显示提示
          setTimeout(() => {
            if (!userData.value.address || userData.value.address.trim() === '' || userData.value.address === '未设置') {
              proxy?.$message?.info('猫猫提醒您：完善好信息才能开始购物哦')
              // 可以选择自动打开编辑弹窗
              // openEditModal()
            }
          }, 500)  // 延迟显示，确保页面已加载完成
        } else {
          console.warn('获取的顾客信息不完整或无效:', response)
        }
      } catch (error) {
        console.error('获取顾客信息失败:', error.message || error)
      }
    }

    // 用户头像计算属性
    const userAvatar = computed(() => {
      // 如果用户有头像，使用用户头像
      if (userData.value.avatarUrl && userData.value.avatarUrl.trim()) {
        return userData.value.avatarUrl
      }
      // 兼容旧的avatar字段
      if (userData.value.avatar && userData.value.avatar.trim()) {
        return userData.value.avatar
      }

      // 否则根据性别使用默认头像
      const gender = userData.value.gender
      // 使用简单的emoji作为默认头像示例
      return gender === 1 ? '👨' : gender === 2 ? '👩' : '👤'
    })

    // 获取性别显示文本
    const getGenderDisplay = (gender) => {
      if (gender === 1) return '男'
      if (gender === 2) return '女'
      return '未设置'
    }

    // 格式化生日
    const formatBirthday = (birthday) => {
      if (!birthday) return '未设置'

      try {
        // 处理不同格式的日期
        const date = new Date(birthday)
        if (isNaN(date.getTime())) return '未设置'

        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      } catch {
        return '未设置'
      }
    }

    // 跳转到登录页面
    const goToLogin = () => {
      router.push('/customer-login')
    }

    // 跳转到注册页面
    const goToRegister = () => {
      router.push('/customer-login')
    }

    // 打开编辑弹窗
    const openEditModal = () => {
      // 填充表单数据，将当前用户数据复制到编辑表单
      editForm.value = {
        id: userData.value.id || '',
        nickname: userData.value.nickname || '',
        gender: userData.value.gender ? String(userData.value.gender) : '',
        // 格式化生日为YYYY-MM-DD格式以适配date输入
        birthday: userData.value.birthday ? new Date(userData.value.birthday).toISOString().split('T')[0] : '',
        address: userData.value.address || ''
      }
      showEditModal.value = true
    }

    // 关闭编辑弹窗
    const closeEditModal = () => {
      showEditModal.value = false
      // 重置表单
      editForm.value = {
        id: '',
        nickname: '',
        gender: '',
        birthday: '',
        address: ''
      }
    }

    // 处理头像选择
    const handleAvatarSelect = (event) => {
      const file = event.target.files[0]
      if (file) {
        // 检查文件类型和大小
        const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
        if (!validTypes.includes(file.type)) {
          proxy?.$message?.error('请上传JPG、PNG、GIF或WebP格式的图片')
          return
        }

        if (file.size > 5 * 1024 * 1024) { // 5MB限制
          proxy?.$message?.error('图片大小不能超过5MB')
          return
        }

        selectedAvatar.value = file
        // 创建图片预览URL
        const reader = new FileReader()
        reader.onload = (e) => {
          avatarPreviewUrl.value = e.target.result
        }
        reader.readAsDataURL(file)
      }
    }

    // 上传头像
    const handleAvatarUpload = async () => {
      if (!selectedAvatar.value) {
        proxy?.$message?.warning('请选择要上传的头像图片')
        return
      }

      // 从userRoles中获取customerId
      const userRolesStr = localStorage.getItem('userRoles')
      let customerId = null
      if (userRolesStr) {
        try {
          const userRoles = JSON.parse(userRolesStr)
          const customerRole = userRoles.find(role => role.code === 'CUSTOMER')
          customerId = customerRole ? customerRole.id : null
        } catch (error) {
          console.error('解析userRoles失败:', error)
        }
      }

      if (!customerId) {
        proxy?.$message?.error('无法获取用户ID，请重新登录')
        return
      }

      uploadingAvatar.value = true
      try {
        const formData = new FormData()
        formData.append('avatar', selectedAvatar.value)
        formData.append('customerId', customerId)

        await updateCustomerAvatar(formData)

        // 重新获取用户信息以更新头像
        await fetchUserDetails(customerId)

        proxy?.$message?.success('头像更新成功')
        showAvatarModal.value = false
        selectedAvatar.value = null
        avatarPreviewUrl.value = null
      } catch (error) {
        console.error('更新头像失败:', error)
        proxy?.$message?.error('头像更新失败，请重试')
      } finally {
        uploadingAvatar.value = false
      }
    }

    // 触发文件选择对话框
    const triggerFileSelect = () => {
      const fileInput = document.getElementById('avatar-upload')
      if (fileInput) {
        fileInput.click()
      }
    }

    // 关闭头像弹窗并重置选择
    const closeAvatarModal = () => {
      showAvatarModal.value = false
      selectedAvatar.value = null
      avatarPreviewUrl.value = null
      // 重置文件输入
      const fileInput = document.getElementById('avatar-upload')
      if (fileInput) {
        fileInput.value = ''
      }
    }

    // 处理更新操作
    const handleUpdate = async () => {
      // 表单验证
      if (!editForm.value.nickname.trim()) {
        proxy?.$message?.warning('昵称不能为空')
        return
      }

      updating.value = true
      try {
        // 构建更新数据对象，注意字段名要与后端CustomerUpdateDTO对应
        const updateData = {
          id: editForm.value.id,
          nickname: editForm.value.nickname.trim(),
          gender: editForm.value.gender ? Number(editForm.value.gender) : null,
          birthday: editForm.value.birthday ? new Date(editForm.value.birthday) : null,
          address: editForm.value.address.trim() || null,
          // 不更新头像
          avatarUrl: userData.value.avatarUrl || null
        }

        console.log('提交更新数据:', updateData)
        // 调用更新API
        await updateCustomerInfo(updateData)

        // 更新成功后，重新获取用户信息以确保数据最新
        await fetchUserDetails(updateData.id)

        // 显示成功提示，与SellerCategoryManage.vue保持一致的消息提示风格
        proxy?.$message?.success('顾客信息更新成功')

        // 关闭弹窗
        closeEditModal()
      } catch (error) {
        console.error('更新顾客信息失败:', error)
        proxy?.$message?.error('更新失败，请重试')
      } finally {
        updating.value = false
      }
    }

    // 退出登录
    const handleLogout = () => {
      // 清除本地存储的用户信息
      localStorage.removeItem('userToken')
      localStorage.removeItem('userRoles')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userId') // 确保清除所有相关登录信息

      // 更新状态
      isLoggedIn.value = false
      userData.value = {}

      // 手动触发storage事件，确保TopNavbar组件能立即感知到状态变化
      // 通过在localStorage中设置一个临时值然后立即删除来触发事件
      const event = new StorageEvent('storage', {
        key: 'userInfo',
        oldValue: localStorage.getItem('userInfo'),
        newValue: null,
        storageArea: localStorage,
        url: window.location.href
      })
      window.dispatchEvent(event)

      // 跳转回首页
      router.push('/')
    }

    // 组件挂载时检查登录状态
    onMounted(() => {
      checkLoginStatus()
    })

    return {
        isLoggedIn,
        userData,
        userAvatar,
        getGenderDisplay,
        formatBirthday,
        goToLogin,
        goToRegister,
        handleLogout,
        showEditModal,
        updating,
        editForm,
        openEditModal,
        closeEditModal,
        handleUpdate,
        showAvatarModal,
        uploadingAvatar,
        selectedAvatar,
        avatarPreviewUrl,
        triggerFileSelect,
        handleAvatarSelect,
        handleAvatarUpload,
        closeAvatarModal
      }
    }
  }

</script>
